package com.example.a_java.service.impl;

import com.example.a_java.dto.MarketingQuery;
import com.example.a_java.dto.PageResult;
import com.example.a_java.entity.Marketing;
import com.example.a_java.mapper.MarketingMapper;
import com.example.a_java.service.MarketingService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 营销活动服务实现
 */
@Service
@RequiredArgsConstructor
public class MarketingServiceImpl implements MarketingService {

    private final MarketingMapper marketingMapper;

    @Override
    public Map<String, Object> getMarketingStatistics(String type) {
        // 获取统计数据
        Map<String, Object> statistics = marketingMapper.selectMarketingStatistics(type);
        if (statistics == null) {
            statistics = new HashMap<>();
            statistics.put("totalActivities", 0);
            statistics.put("activityRate", 0);
            statistics.put("participants", 0);
            statistics.put("participantRate", 0);
            statistics.put("conversionAmount", new BigDecimal("0"));
            statistics.put("conversionRate", 0);
            statistics.put("roi", 0);
            statistics.put("roiRate", 0);
        }
        return statistics;
    }

    @Override
    public PageResult<Marketing> getMarketingList(MarketingQuery query) {
        // 查询活动总数
        Long total = marketingMapper.countMarketings(query);
        if (total == 0) {
            return PageResult.build(0L, List.of());
        }
        // 查询活动列表
        List<Marketing> marketings = marketingMapper.selectMarketingList(query);
        return PageResult.build(total, marketings);
    }

    @Override
    public Marketing getMarketingById(Long id) {
        return marketingMapper.selectMarketingById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addMarketing(Marketing marketing) {
        // 检查活动时�?
        checkMarketingTime(marketing);
        // 设置创建时间和更新时�?
        LocalDateTime now = LocalDateTime.now();
        marketing.setCreateTime(now);
        marketing.setUpdateTime(now);
        // 设置默认状�?
        if (marketing.getStatus() == null) {
            marketing.setStatus("planning");
        }
        // 设置默认参与人数和转化金�?
        if (marketing.getParticipants() == null) {
            marketing.setParticipants(0);
        }
        if (marketing.getConversionAmount() == null) {
            marketing.setConversionAmount(new BigDecimal("0"));
        }
        // 插入活动
        marketingMapper.insertMarketing(marketing);
        return marketing.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMarketing(Marketing marketing) {
        // 检查活动时�?
        checkMarketingTime(marketing);
        // 设置更新时间
        marketing.setUpdateTime(LocalDateTime.now());
        // 更新活动
        marketingMapper.updateMarketing(marketing);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMarketings(String ids) {
        // 将ID字符串转换为ID列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());
        // 检查活动状�?
        int ongoingCount = marketingMapper.countOngoingMarketings(idList);
        if (ongoingCount > 0) {
            throw new RuntimeException("进行中的活动不能删除");
        }
        // 删除活动
        marketingMapper.deleteMarketingByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMarketingStatus(Marketing marketing) {
        // 检查活动状�?
        if ("finished".equals(marketing.getStatus())) {
            // 结束活动时检查活动是否存�?
            Marketing existMarketing = marketingMapper.selectMarketingById(marketing.getId());
            if (existMarketing == null) {
                throw new RuntimeException("活动不存在");
            }
        }
        // 设置更新时间
        marketing.setUpdateTime(LocalDateTime.now());
        // 更新活动状�?
        marketingMapper.updateMarketingStatus(marketing);
    }

    /**
     * 检查活动时�?
     *
     * @param marketing 活动信息
     */
    private void checkMarketingTime(Marketing marketing) {
        if (marketing.getStartTime() == null || marketing.getEndTime() == null) {
            throw new RuntimeException("活动开始时间和结束时间不能为空");
        }
        if (marketing.getStartTime().isAfter(marketing.getEndTime())) {
            throw new RuntimeException("活动开始时间不能晚于结束时间");
        }
        if (marketing.getStartTime().isBefore(LocalDateTime.now()) && !"ongoing".equals(marketing.getStatus())) {
            marketing.setStatus("ongoing");
        }
    }
} 
